import 'dart:async';

import 'package:flutter_axrjc/datasource/network/bean/EventBean.dart';
import 'package:flutter_axrjc/main.dart';
import 'package:sensors_plus/sensors_plus.dart';

class AccelerationUtil {
  final double _shakeThreshold = 3.0;
  AccelerometerEvent _previousAcc = AccelerometerEvent(0, 0, 0);
  bool _isStartCheck = false;
  StreamSubscription<AccelerometerEvent>? _sensorListener;
  AccelerationUtil() {
    _sensorListener =
        accelerometerEventStream().listen((AccelerometerEvent event) async {
      if (!_isStartCheck) return;
      // 解决一开始就判断抖动的问题
      if (_previousAcc.x == 0 && _previousAcc.y == 0 && _previousAcc.z == 0) {
        _previousAcc = event;
        return;
      }
      double deltaX = event.x - _previousAcc.x;
      double deltaY = event.y - _previousAcc.y;
      double deltaZ = event.z - _previousAcc.z;
      double acceleration = deltaX.abs() + deltaY.abs() + deltaZ.abs();
      if (acceleration > _shakeThreshold) {
        eventBus.fire(EventBean(type: EventType.mobildMoving, data: null));
        _previousAcc = event;
      }
    });
  }
  void startCheck() {
    _isStartCheck = true;
  }

  void interrupt() {
    _isStartCheck = false;
  }

  void onClose() {
    _sensorListener?.cancel();
  }
}
